package com.xingdata.jjxc.activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.adapter.NaviHistoryListViewAdapter;
import com.xingdata.jjxc.base.BaseActivity;
import com.xingdata.jjxc.enty.NaviHistoryEntity;
import com.xingdata.jjxc.record.MyCustomListView;
import com.xingdata.jjxc.record.RecordSQLiteOpenHelper;
import com.xingdata.jjxc.utils.JUtils;
import java.util.ArrayList;
import java.util.UUID;
import com.xingdata.jjxc.R;
/** 
 * 
 * @Description: 点击导航主页面的导航按钮
 * @date 2016-10-11 下午10:36:55 Creater yy
 */
public class NaviCompactActivity extends BaseActivity implements OnItemClickListener  {
	
	private static String TAG = NaviCompactActivity.class.getSimpleName();

	private ArrayList<NaviHistoryEntity> naviHistoryEntityList = new ArrayList<NaviHistoryEntity>();
	private NaviHistoryListViewAdapter adapter;
	private RelativeLayout rl_location_settings;
	private LinearLayout ll_navi_settings;

	/** 清除按钮 */
	private Button btn_clear_record;
	private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
	private SQLiteDatabase db;
	private MyCustomListView search_record_listview;
	

	
	@Override
	protected int getContentViewId() {
		return R.layout.navi_compact_search;
	}

	@Override
	protected String getTitleText() {
		return null;
	}
	
	/**搜索记录初始化*/
	private void initSearchRecord() {
		// 修改字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
		
		/*搜索历史列表*/
		search_record_listview = (MyCustomListView) findViewById(R.id.search_record_listview);
		search_record_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//todo
				startNavi(from,to,pass);
//				Toast.makeText(NaviCompactActivity.this, name, Toast.LENGTH_SHORT).show();
			}
		});
		adapter = new NaviHistoryListViewAdapter(naviHistoryEntityList, this);
		search_record_listview.setAdapter(adapter);
		search_record_listview.setOnItemClickListener(this);
		
		/*清除记录按钮*/
		btn_clear_record = (Button) findViewById(R.id.btn_clear_record); 
		btn_clear_record.setTypeface(font);
		btn_clear_record.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clearData();
				queryData("");
			}
		});
		
		// 第一次进入查询所有的历史记录
//		insertData("test","test","test","test");
		queryData("");
	}
	
	/**
	 * 插入数据
	 */
	private void insertData(String tempName,String address,String lat,String lng) {
		try{
			db = helper.getWritableDatabase();
			Cursor cursor = db.rawQuery(
					"select id as _id,name,address,lat,lng from navirecords where name = '" + tempName + "' order by id desc ", null);
			if(!cursor.moveToNext()){
				db.execSQL("insert into navirecords(name,address,lat,lng) values('" + tempName + "','"+address+"','"+lat+"','"+lng+"')");
			}
			cursor.close();

		}catch(Exception ex){
			ex.printStackTrace();
			Log.e(TAG,ex.toString());
		}finally {
			db.close();
		}

	}

	/**
	 * 模糊查询数据
	 */
	private void queryData(String tempName) {
		SQLiteDatabase db = helper.getReadableDatabase();
		try{
			Cursor cursor = db.rawQuery(
					"select id as _id,name,address,lat,lng from navirecords where name like '%" + tempName + "%' order by id desc ", null);
			while(cursor.moveToNext()){
				NaviHistoryEntity naviHistoryEntity = new NaviHistoryEntity();
				naviHistoryEntity.setloca_id(UUID.randomUUID().toString());
				naviHistoryEntity.setloca_nickname(cursor.getString(cursor.getColumnIndex("name")));
				naviHistoryEntity.setloca_address(cursor.getString(cursor.getColumnIndex("address")));
				naviHistoryEntity.setloca_lng(cursor.getString(cursor.getColumnIndex("lng")));
				naviHistoryEntity.setloca_lat(cursor.getString(cursor.getColumnIndex("lat")));

				naviHistoryEntityList.add(naviHistoryEntity);

				btn_clear_record.setVisibility(naviHistoryEntityList.size()>0 ? View.VISIBLE:View.GONE);

			}

			cursor.close();

			adapter.notifyDataSetChanged();
		}catch(Exception ex){
			ex.printStackTrace();
			Log.e(TAG,ex.toString());
		}finally {
			db.close();
		}

	}
	
	/**
	 * 检查数据库中是否已经有该条记录
	 */
	private boolean hasData(String tempName) {
		SQLiteDatabase db = helper.getReadableDatabase();
		try{
			Cursor cursor = db.rawQuery(
					"select id as _id,name,address,lat,lng from navirecords where name =?", new String[]{tempName});
			//判断是否有下一个
			return cursor.moveToNext();
		}catch(Exception ex){
			ex.printStackTrace();
			Log.e(TAG,ex.toString());
		}finally {
			db.close();
		}

		return false;
	}

	/**
	 * 清空数据
	 */
	private void clearData() {
		db = helper.getWritableDatabase();
		db.execSQL("delete from navirecords");
		db.close();
		naviHistoryEntityList.clear();
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		from.setPlace_name(getIntent().getStringExtra(NAME));
		from.setPlace_address(getIntent().getStringExtra(ADDRESS));
		from.setPlace_lat(getIntent().getStringExtra(LAT));
		from.setPlace_lng(getIntent().getStringExtra(LNG));
		ed_pos_start.setText(from.getPlace_name());

		initSearchRecord();

	}


	private TextView ed_pos_start;
	private TextView ed_pos_pass;
	private LinearLayout ll_split_pass;
	private TextView ed_pos_end;
	private ImageView iv_switch;
	private ImageView iv_addpass;

	private ComEntity from = new ComEntity();
	private ComEntity to = new ComEntity();
	private ComEntity pass = new ComEntity();

	private static final int REQUEST_CODE_START=0;
	private static final int REQUEST_CODE_PASS=2;
	private static final int REQUEST_CODE_END=1;

	@Override
	protected void initViews() {
		
		// 修改字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);

		((ImageView) findViewById(R.id.goBack)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});


		ed_pos_start = (TextView)findViewById(R.id.ed_pos_start);
		ed_pos_start.setTypeface(font);
		ed_pos_pass  = (TextView)findViewById(R.id.ed_pos_pass);
		ed_pos_pass.setTypeface(font);
		ll_split_pass = (LinearLayout)findViewById(R.id.ed_pos_pass_split);
		ed_pos_end  = (TextView)findViewById(R.id.ed_pos_end);
		ed_pos_end.setTypeface(font);

		//set listener
		ed_pos_start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(NAME,from.getPlace_name());
				bundle.putString(ADDRESS,from.getPlace_address());
				bundle.putString(LAT,from.getPlace_lat());
				bundle.putString(LNG,from.getPlace_lng());
				Intent intent = new Intent(NaviCompactActivity.this,NaviSerchActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent,REQUEST_CODE_START);
			}
		});

		ll_split_pass.setVisibility(View.GONE);
		ed_pos_pass.setVisibility(View.GONE);
		ed_pos_pass.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(NAME,pass.getPlace_name());
				bundle.putString(ADDRESS,pass.getPlace_address());
				bundle.putString(LAT,pass.getPlace_lat());
				bundle.putString(LNG,pass.getPlace_lng());
				Intent intent = new Intent(NaviCompactActivity.this,NaviSerchActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent,REQUEST_CODE_PASS);

			}
		});
//		ed_pos_end.requestFocus();
		ed_pos_end.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(NAME,to.getPlace_name());
				bundle.putString(ADDRESS,to.getPlace_address());
				bundle.putString(LAT,to.getPlace_lat());
				bundle.putString(LNG,to.getPlace_lng());
				Intent intent = new Intent(NaviCompactActivity.this,NaviSerchActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent,REQUEST_CODE_END);
			}
		});


		iv_switch = (ImageView) findViewById(R.id.search_home_switch);
		findViewById(R.id.search_home_switch_layout).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				ComEntity tmp = to;
				to = from;
				ed_pos_end.setText(to.isValid()?to.getPlace_name():"");
				ed_pos_end.setHint("");
				from = tmp;
				ed_pos_start.setText(from.isValid()?from.getPlace_name():"");
				ed_pos_start.setHint("");
			}
		});
		iv_addpass = (ImageView) findViewById(R.id.search_addpass);
		findViewById(R.id.search_addpass_layout).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(ll_split_pass.getVisibility() != View.VISIBLE){
					ll_split_pass.setVisibility(View.VISIBLE);
					ed_pos_pass.setVisibility(View.VISIBLE);
					iv_addpass.setBackgroundResource(R.drawable.icon_delete);
				}else{
					ll_split_pass.setVisibility(View.GONE);
					ed_pos_pass.setVisibility(View.GONE);
					iv_addpass.setBackgroundResource(R.drawable.icon_increase);
				}

			}
		});
		//导航设置
		findViewById(R.id.navi_settings_layout).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NaviCompactActivity.this,NaviSetActivity.class);
				startActivityForResult(intent,0);
			}
		});

		rl_location_settings = (RelativeLayout)findViewById(R.id.location_settings);


	}

	private void startNavi(ComEntity from,ComEntity to,ComEntity pass){
		Log.i(TAG,"start navi:from="+from.getPlace_name()+";to="+to.getPlace_name());
		if (ll_split_pass.getVisibility() != View.VISIBLE){

		}

		insertData(to.getPlace_name(),to.getPlace_address(),to.getPlace_lat(),to.getPlace_lng());

		//adapter.notifyDataSetChanged();
		Bundle bundle = new Bundle();
		bundle.putSerializable("from",from);
		bundle.putSerializable("pass",pass);
		bundle.putSerializable("to",to);
		Intent intent = new Intent();
		intent.putExtras(bundle);
		setResult(RESULT_OK,intent);
		finish();
	}


	private static final String NAME = "name";
	private static final String ADDRESS = "address";
	private static final String LAT = "lat";
	private static final String LNG = "lng";
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != RESULT_OK) {
			return;
		}

		ComEntity mapEnity = (ComEntity)data.getSerializableExtra("poi");
		if(null == mapEnity){
			Log.e(TAG,"没有坐标");
			return;
		}
//		NaviHistoryEntity hisEnity = (NaviHistoryEntity)data.getSerializableExtra("poi");
//		if(null != hisEnity){
//			if(null == mapEnity)
//				mapEnity = new ComEntity();
//			mapEnity.setPlace_name(hisEnity.getloca_nickname());
//			mapEnity.setPlace_address(hisEnity.getloca_address());
//			mapEnity.setPlace_lng(hisEnity.getloca_lng());
//			mapEnity.setPlace_lat(hisEnity.getloca_lat());
//		}



		switch (requestCode) {
		case REQUEST_CODE_START:
//			from.setPlace_name(data.getStringExtra(NAME));
//			from.setPlace_address(data.getStringExtra(ADDRESS));
//			from.setPlace_lat(data.getStringExtra(LAT));
//			from.setPlace_lng(data.getStringExtra(LNG));
			from = mapEnity;
			if(from!=null && from.isValid())
				ed_pos_start.setText(from.getPlace_name());
			break;
			
		// 设置公司地址返回结果	
		case REQUEST_CODE_PASS:
//			pass.setPlace_name(data.getStringExtra(NAME));
//			pass.setPlace_address(data.getStringExtra(ADDRESS));
//			pass.setPlace_lat(data.getStringExtra(LAT));
//			pass.setPlace_lng(data.getStringExtra(LNG));
			pass = mapEnity;
			if(pass!=null && pass.isValid())
				ed_pos_pass.setText(pass.getPlace_name());
			break;
		
		case REQUEST_CODE_END:
//			to.setPlace_name(data.getStringExtra(NAME));
//			to.setPlace_address(data.getStringExtra(ADDRESS));
//			to.setPlace_lat(data.getStringExtra(LAT));
//			to.setPlace_lng(data.getStringExtra(LNG));
			to = mapEnity;

			if (null != to && to.isValid()){
				ed_pos_end.setText(to.getPlace_name());
			}
			//开始导航
			if(from.isValid() && to.isValid())
				startNavi(from,to,pass);

		break;

		default:
			break;
		}
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
		NaviHistoryEntity naviHistoryEntity = naviHistoryEntityList.get(position);
		to.setPlace_name(naviHistoryEntity.getloca_nickname());
		to.setPlace_address(naviHistoryEntity.getloca_address());
		to.setPlace_lat(naviHistoryEntity.getloca_lat());
		to.setPlace_lng(naviHistoryEntity.getloca_lng());

		ed_pos_end.setText(to.getPlace_name());


		//开始导航
		if(from.isValid() && to.isValid())
			startNavi(from,to,pass);

	}





}
